package xyz.csmcool.imoss.service.impl;



import lombok.RequiredArgsConstructor;
import org.csource.common.MyException;
import org.csource.fastdfs.ClientGlobal;
import org.csource.fastdfs.StorageClient;
import org.csource.fastdfs.TrackerClient;
import org.csource.fastdfs.TrackerServer;
import org.springframework.stereotype.Component;
import xyz.csmcool.imoss.config.UploadTypeEnum;
import xyz.csmcool.imoss.entity.OssConfig;
import xyz.csmcool.imoss.mapper.OssConfigMapper;
import xyz.csmcool.imoss.service.UploadFile;
import xyz.csmcool.imoss.utils.FileUtil;

import java.io.File;
import java.io.IOException;
import java.net.URL;

/**
 * @author 什锦
 * @Package xyz.csmcool.imoss.service.impl
 * @since 2022/8/5 14:33
 */

@Component
@RequiredArgsConstructor
public class FastdfsUpload implements UploadFile {

    final OssConfigMapper ossConfigMapper;

    @Override
    public UploadTypeEnum getUploadType() {
        return UploadTypeEnum.FASTDFS;
    }

    @Override
    public String upload(File file, String prefix) {
        OssConfig ossConfig = ossConfigMapper.selectConfig();
        String url = ossConfig.getUrl();
        try {
            URL url1 = new URL(url);
            String host = url1.getHost();
            ClientGlobal.initByTrackers(host + ":22122");
            //创建于tracker交互的客户端
            TrackerClient trackerClient  = new TrackerClient();
            //通过客户端与tracker建立连接
            TrackerServer trackerServer = trackerClient.getTrackerServer();
            //通过tracker服务端获取一个可以使用的storage客户端
            StorageClient storageClient = new StorageClient(trackerServer, null);
            //上传文件，只需要一个文件路径
            String name = file.getName();
            String extName = name.substring(name.lastIndexOf(".") + 1);
            String[] strings = storageClient.upload_appender_file(FileUtil.File2byte(file), extName, null);
            return url + "/" + strings[0] + "/" + strings[1];
        } catch (IOException e) {
            e.printStackTrace();
        } catch (MyException e) {
            e.printStackTrace();
        }
        return null;
    }
}
